$(function () {
    var query = {}, fields = 'id|userName|password|name|gender|phone|comid|depid', fields_ = 'id|name',
        $search = $('.search'), user_roles = {};
    var config = {
        coloum_num: 8, //列数目
        query: '/ads/query?',//分页查询URL,
        query_com: '/com/query?',//分页查询URL,
        query_dep: '/dep/query?',//分页查询URL,
        query_role: '/role/list?',//分页查询URL,
        create: '/user/create',//create,
        update: '/ads/update',
        role_update: '/user/role_update',
        get_user_role: '/user/get_user_role',
        'delete': '/ads/delete',
    };

    var searchObj = parseSearch();
    $('.upload').click(function () {
        window.location.href = './img.html?type=' + (searchObj.type || '0');
    });
    if(searchObj){
        $('.nav-primary li:nth-child('+(parseInt(searchObj.type||0)+1)+')').addClass('active').siblings('.active').removeClass('active');
    }
    function search(obj,isForce) {
        var query_ = {};
        $.extend(query_, query, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        if (!isForce) {
            if (isSameQueryStr(query_, query)) { //查询条件和上次一样，取消请求
                return $loading.fadeOut();
            }
        }
        var arg = [];
        query_.type = searchObj.type||0;
        Object.keys(query_).map(function (key) {
            arg.push(key + '=' + query_[key])
        });
        query = query_;query.timestamp = Date.now(); 
        $.get(config.query + arg.join('&'), function (res) {
            if (res.list.length) {
                render(res.list)
            } else {
                render(noData(config.coloum_num));
                $('.reset-query').click(function () {
                    $search.val('');
                })
            }
            var page = res.page || {};
            pageInit(page, query, search);
        });
    }

    function render(list) {

        $('.table-responsive .table tbody').html('');
        if (list instanceof Array) {
            list.forEach(function (item, index) {
                console.log(item.type == '1');
                $('.table-responsive .table tbody')
                    .append('<tr> \
                    <td scope="row">' + (index + 1) + ' \
                </td> \
                <td>' + item.order + '</td> \
                <td>' + ((item.type == '1') ? '详情广告' : ((item.type == '0') ? '首页广告' : '微信详情广告')) + '</td> \
                <td><a href="' + item.url + '" target="_blank">' + (item.url) + '</a></td> \
                <td><a href="' + (item.link || 'javascript:void(0);') + '" target="_blank">' + (item.link || '') + '</a></td> \
                <td>' + (item.status == DATA_STATUS.ONLINE ? '上线' : '下线') + '</td> \
                <td class="text-left" style="width: 140px;padding:1px 8px;"> \
                <div class="btn-group"  >\
                 ' + (item.status == DATA_STATUS.ONLINE ? '<button type="button" class="btn btn-xs  btn-danger opt-offline"   data-loading-text="下线中.." data-json=\'' + JSON.stringify(item) + '\'>下线</button>' :
                        '<button type="button" class="btn btn-xs  btn-success opt-online"   data-loading-text="上线中.." data-json=\'' + JSON.stringify(item) + '\'>上线</button>') + '\
                <button type="button" class="btn btn-xs  btn-danger opt-delete"   data-loading-text="删除.." data-json=\'' + JSON.stringify(item) + '\'>删除</button> \
                </div> \
                '+(item.status == DATA_STATUS.OFFLINE?'<a href="img.html?type='+item.type+'&edit=true&id='+item.id+'"  >编辑</a>':'')+' \
                </td> \
                </tr>')
            });
            $('.opt-delete').click(function () {
                $(this).closest('tr').addClass('active').siblings('tr').removeClass('active');
                var self = this;
                $(this).button('loading');
                var item = $(this).data('json');
                if (confirm('确认删除？')) {
                    $.post(config['update'], {id: item.id, status: 0}, function (xhr, data) {
                        $(self).button('reset');
                        if (xhr.code == 200) {
                            $(self).closest('tr').remove()
                        } else {
                            alert(xhr.error);
                        }
                    });
                } else {
                    $(self).button('reset');
                }
            });
            $('.opt-online').click(function () {
                $(this).closest('tr').addClass('active').siblings('tr').removeClass('active');
                var self = this;
                $(this).button('loading');
                var item = $(this).data('json');
                $.post(config['update'], {id: item.id, status: 1}, function (xhr, data) {
                    $(self).button('reset');
                    if (xhr.code == 200) {
                        fnSuccess('操作成功!');
                        search({},true);
                    } else {
                        alert(xhr.error);
                    }
                });
            });
            $('.opt-offline').click(function () {
                $(this).closest('tr').addClass('active').siblings('tr').removeClass('active');
                var self = this;
                $(this).button('loading');
                var item = $(this).data('json');
                $.post(config['update'], {id: item.id, status: 2}, function (xhr, data) {
                    $(self).button('reset');
                    if (xhr.code == 200) {
                        fnSuccess('操作成功!');
                        search({},true);
                    } else {
                        alert(xhr.error);
                    }
                });
            });
        } else {
            $('.table-responsive .table tbody').html(list);
        }
        $loading.fadeOut();
    }

    search({},true);
    // 表单提交
    var $submit = $('#submit'), $submitrole = $('#submit-role');


    $('.table th .fa').click(function (e) {
        var sort = {sortField: '', sortOrder: ''};
        sort.sortField = $(this).data('sort');
        if ($(this).hasClass('fa-sort') || $(this).hasClass('fa-sort-desc')) {
            sort.sortOrder = 'ASC';
            $(this)
                .removeClass('fa-sort-desc fa-sort')
                .addClass('fa-sort-asc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort');
        } else if ($(this).hasClass('fa-sort-asc')) { //asc
            sort.sortOrder = 'DESC';
            $(this)
                .removeClass('fa-sort-asc fa-sort')
                .addClass('fa-sort-desc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort')
        }
        search(sort);
    })
});